import React, { useState, useEffect } from 'react';
import { Box, Grid, GridItem, Flex, Heading, Text, useDisclosure, Button, useToast } from '@chakra-ui/react';
import MethodSearch from '../components/MethodSearch';
import NodeTree from '../components/NodeTree';
import NodeDetails from '../components/NodeDetails';
import { ExternalLinkIcon } from '@chakra-ui/icons';
import { disconnectFromDatabase, checkConnectionStatus, getSessionId } from '../api/api';

const Dashboard = ({ onLogout }) => {
  const [selectedMethod, setSelectedMethod] = useState(null);
  const [selectedNodeId, setSelectedNodeId] = useState(null);
  const [connectionCheckFailed, setConnectionCheckFailed] = useState(false);
  const toast = useToast();

  // 在组件加载时检查后端连接状态
  useEffect(() => {
    const verifyConnection = async () => {
      // 如果没有会话ID，直接返回登录页
      if (!getSessionId()) {
        console.log('未检测到会话ID，返回登录页');
        localStorage.removeItem('nebula_connection_status');
        onLogout();
        return;
      }

      try {
        // 调用后端API检查连接状态
        await checkConnectionStatus();
        // 重置连接检查失败状态
        if (connectionCheckFailed) {
          setConnectionCheckFailed(false);
          toast({
            title: '连接已恢复',
            description: '与数据库的连接已恢复',
            status: 'success',
            duration: 3000,
            isClosable: true,
          });
        }
      } catch (error) {
        console.error('验证数据库连接失败:', error);
        
        // 如果是首次失败，显示提示
        if (!connectionCheckFailed) {
          setConnectionCheckFailed(true);
          toast({
            title: '连接问题',
            description: '数据库连接异常，正在尝试重新连接...',
            status: 'warning',
            duration: 5000,
            isClosable: true,
          });
          
          // 延迟3秒后重试
          setTimeout(verifyConnection, 3000);
        } else {
          // 如果已经失败过，认为连接彻底断开
          toast({
            title: '连接已断开',
            description: '数据库连接已断开，请重新连接',
            status: 'error',
            duration: 5000,
            isClosable: true,
          });
          // 清除连接状态并返回登录页
          localStorage.removeItem('nebula_connection_status');
          onLogout();
        }
      }
    };

    verifyConnection();
    
    // 定期检查连接状态
    const connectionInterval = setInterval(verifyConnection, 30000);
    
    return () => {
      clearInterval(connectionInterval);
    };
  }, [onLogout, toast, connectionCheckFailed]);

  const handleMethodSelect = (method) => {
    console.log("选择方法:", method);
    setSelectedMethod(method);
    // 如果方法有节点ID，直接设置为选中节点，否则重置为null
    setSelectedNodeId(method.nodeId || null);
  };

  const handleNodeClick = (nodeId) => {
    console.log("点击节点, 设置selectedNodeId:", nodeId);
    setSelectedNodeId(nodeId);
  };

  const handleDisconnect = async () => {
    try {
      await disconnectFromDatabase();
      // 只清除连接状态，保留连接信息
      localStorage.removeItem('nebula_connection_status');
      // 不删除 nebula_connection_info，这样下次用户连接时可以记住上次的连接设置
      onLogout();
    } catch (error) {
      console.error('断开连接失败:', error);
      // 即使失败也清除连接状态并返回登录页
      localStorage.removeItem('nebula_connection_status');
      // 不删除 nebula_connection_info
      onLogout();
    }
  };

  console.log("Dashboard渲染状态:", { selectedMethod, selectedNodeId });

  return (
    <Box p={4} maxWidth="100%">
      <Flex align="center" justify="space-between" mb={8}>
        <Heading as="h1" size="lg">码灵控制台</Heading>
        <Button 
          leftIcon={<ExternalLinkIcon />} 
          variant="outline" 
          size="sm" 
          onClick={handleDisconnect}
        >
          断开连接
        </Button>
      </Flex>

      <Grid
        templateColumns={{ base: "1fr", lg: "300px 1fr" }}
        gap={6}
      >
        {/* 左侧搜索区域 */}
        <GridItem>
          <MethodSearch onMethodSelect={handleMethodSelect} />
        </GridItem>

        {/* 右侧可视化区域 */}
        <GridItem>
          <Grid
            templateRows={{ base: "repeat(2, auto)", lg: "1fr" }}
            templateColumns={{ base: "1fr", lg: "1fr 350px" }}
            gap={6}
          >
            {/* 上部/左侧: 节点树状图 */}
            <GridItem>
              {selectedMethod ? (
                <NodeTree methodData={selectedMethod} onNodeClick={handleNodeClick} />
              ) : (
                <Box p={5} shadow="md" borderWidth="1px" borderRadius="md" bg="white" height="400px">
                  <Heading size="md" mb={4}>方法关系树</Heading>
                  <Text>请先从左侧搜索并选择一个方法节点</Text>
                </Box>
              )}
            </GridItem>

            {/* 下部/右侧: 节点详情 */}
            <GridItem>
              <NodeDetails nodeId={selectedNodeId} />
            </GridItem>
          </Grid>
        </GridItem>
      </Grid>
    </Box>
  );
};

export default Dashboard; 